package com.milo.common.utils;

import cn.hutool.core.lang.UUID;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.util.Base64;

/**
 * Base64工具类
 * @author Milo Lee
 * @date 2021-12-02 15:03
 */
public class Base64Util {

    /***
     * 获取文件的base64加密值
     * @author Milo Lee
     * @date 2021-12-02 15:05
     * @param file 文件对象
     * @return java.lang.String
     */
    public static String getBase64File(File file) {
        InputStream is = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            is = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while ((n = is.read(b)) != -1) {
                out.write(b, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }

        byte[] bytes = out.toByteArray();
        return Base64.getEncoder().encodeToString(bytes);
    }


    /***
     * 将base64输出为文件
     * @author Milo Lee
     * @date 2021-12-02 17:22
     * @param data 加密数据
     */
    private static  void writeFile (String  data){
        try {
            IOUtils.copyLarge(new ByteArrayInputStream(Base64.getDecoder().decode(data)),
                    new FileOutputStream("E:/" + UUID.randomUUID().toString() + ".pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String base64File = Base64Util.getBase64File(new File("E:\\兰州大学榆中校区工程科学组团I工程监理评标报告.pdf"));
        Base64Util.writeFile(base64File);

    }

}
